const app = getApp()
import {
  getToken
} from '../../utils/util.js'
import request from "../../utils/request";
var api = require("../../utils/api");
const {
  $Message
} = require('../commpoents/iview-dist/base/index.js');
var timeAuto = null
var lastPlayId = null
var setTime = null
const host = "https://neikong.chinahonden.com/"
var formId = ''
var allVoice = []
var innerAudioContext = null
Page({
  data: {
    typeTitle:'投诉',
    sumTitleL: 20,
    sumTxtL: 1000,
    textNowL: 0,
    classId: 0,
    startRecord: false,
    bePlaying: false,
    startRecordTime: 0,
    tempVoice: [], // 音频临时路径
    fileArr: [],
    sumSize: 0,
    title: '',
    content: '',
    phone: '',
    allFileArr: '',
    visible: false,
    rowId: 0,// itemID
    inputValue: '',
    record: [],
    onActiveId: null
  },
  onLoad(option) {
    allVoice = []
    app.getLocalData()
    app.globalData.sendWebFileArr =[]
    var rowId = Number(option.rowId); //投诉类型
    this.setData({
      rowId: rowId
    })
    //获取 上页面传过来的数据，
    let lastBossEditData =  app.globalData.nexPageData
    let voiceStr = ''
    if (lastBossEditData.record.length>0){
      lastBossEditData.record.forEach(item => {
        if (!voiceStr) {
          voiceStr = item + ','
        } else {
          voiceStr = voiceStr + item + ","
        }
      })
    }
    debugger
    innerAudioContext = wx.createInnerAudioContext()
    this.setData({
      record: lastBossEditData.record || [],
      inputValue: lastBossEditData.bossReply || '',
      content: lastBossEditData.bossReply || '',
      allFileArr: voiceStr
    })
  },
  onShow() {
    //检测是否从上个页面返回的
    if (app.globalData.backPage) {
      app.globalData.backPage = false
    } else {
      this.setData({
        tempVoice: [] // 每次音频清空
      })
      app.globalData.fileArr = []
    }
    //检查本页面是否有上传文件
    if (app.globalData.fileArr && app.globalData.fileArr.file && app.globalData.fileArr.file.length > 0) {
      this.checkFile(app.globalData.fileArr)
      this.setData({
        allFileArr: app.globalData.fileArr.file + ','
      })
      $Message({
        content: '上传文件成功',
        type: 'success'
      });
    }else{
      if (app.globalData.fileArr.up && app.globalData.fileArr.up === 1){
        app.globalData.sendWebFileArr = ''
        this.setData({
          fileArr: []
        })
      }
    }
  },
  onReady: function (e) {
    this.recorderManager = wx.getRecorderManager()
  },
  onUnload() {
    clearTimeout(setTime)
      innerAudioContext.destroy()
  },
  onUploadPage(){
    wx.getSystemInfo({
      success: function (res) {
        if (res.model.indexOf('iPhone')>=0){
          var sys = res.system.replace(/\s+/g, '').replace('iOS', '').replace(/\./g, '')        
          var sysNum = Number(sys)
          if (sysNum < 1034){
            //检查系统版本
            wx.navigateTo({
              url: "/pages/complaints/uploadPhone/uploadPhone",
            })
          }else{
            //检查系统版本
            wx.navigateTo({
              url: "/pages/complaints/upload/upload",
            })
          }
        }else{
          //检查系统版本
          wx.navigateTo({
            url: "/pages/complaints/upload/upload",
          })
        }
      }
    })
  },
  // 播放语音
  startVoice(e) {
    var self = this
    var a1 = 0
    var a2 = 0
    var a3 = 0
    var a4 = 0
    var playItem = e.currentTarget.dataset.item
    var lastPlayItem = ''
    innerAudioContext.src = playItem
    innerAudioContext.obeyMuteSwitch = false
    innerAudioContext.play()
    self.setData({
      onActiveId: e.currentTarget.dataset.id
    })
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    })
    innerAudioContext.onEnded(() => {
      console.log('播放结束')
      self.setData({
        onActiveId: null
      })
      innerAudioContext.stop()
    })
    // innerAudioContext.onStop(() => {
    //   console.log('播放tz')
    //   self.setData({
    //     onActiveId: null
    //   })
    //   innerAudioContext.stop()
    // })
    innerAudioContext.onError((res) => {
      self.setData({
        onActiveId: null
      })
      innerAudioContext.stop()
    })
  },
  //打开model
  handleOpen() {
    this.setData({
      visible: true
    });
  },
  onOk(num){
    this.setData({
      visible: false
    });
    if(num === 0){
      //点击确定
    }else{
      //点击取消

    }
  },
  checkRecord(){
    var self = this
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.record']){
         // 成功获取权限
       }else {
         //无录音权限 弹出框让用户主动开启
          self.handleOpen()
       }
      }
    })
  },
  formSubmit(e) {
    formId = e.detail.formId
  },
  getUserInfo(e) {
    var self = this
    if (app.globalData.loginInfo.openid !== '' && app.globalData.loginInfo.openid) {
      this.uploadAll()
    } else {
      if (e.detail.errMsg === "getUserInfo:ok") {
        var rawData = JSON.parse(e.detail.rawData);
        var enData = {}
        app.userLogin(enData).then(res => {
          //登录成功
          try {
            if (res) {
              self.uploadAll()
            }
          } catch (e) {
            console.log(e)
          }
        });
      } else {
        wx.showToast({
          icon: "none",
          title: "微信授权失败",
        });
      }
    }
  },
  uploadAll() {
    debugger
    var url = api.SectetBossReply
    var params = {
      id: this.data.rowId,
      bossReply: this.data.content,
      record: this.data.allFileArr 
    }
    request(url, params, "POST").then(res => {
      if (res.code === 0) {
        $Message({
          content: '提交成功',
          type: 'success'
        });
        this.setData({
          inputValue:"",
          content: "",
          allFileArr: ''
        });
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 1000);
      } else if (res.code === "1020011"){
        wx.showModal({
          content: '需要关注公众号才能收到消息哦',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.previewImage({
                current: 'https://neikong.chinahonden.com/static/module/api/imgs/ewm.png', // 当前显示图片的http链接
                urls: ['https://neikong.chinahonden.com/static/module/api/imgs/ewm.png'] // 需要预览的图片http链接列表
              })
            } else if (res.cancel) {
              
            }
          }
        })
      }
    })
  },
  changeTitle(e) {
    var num = e.detail.cursor
    if (num >= this.data.sumTitleL) {
      $Message({
        content: '最多可写20字',
        type: 'warning'
      });
      return
    }
    this.setData({
      title: e.detail.value
    })
  },
  changePhone(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  checkFile(e) {
    var fileArr = e.file.split(",")
    var size = e.size.split(",")
    //图片和文件分类
    var relArr = []
    var sumSize = 0
    var isImg = (/.jpg$|.png$|.jpeg$|.gif$/i)
    fileArr.forEach((item, id) => {
      var obj = {}
      var isImg = (/.jpg$|.png$|.jpeg$|.gif$/i)
      if (isImg.test(item)) {
        obj.imgPath = item
      } else {
        obj.imgPath = ''
        obj.path = item
      }
      var itemSize = Number(size[id])
      obj.size = itemSize
      sumSize += itemSize
      relArr.push(obj)
    })
    var str = JSON.stringify(relArr)
    app.globalData.sendWebFileArr = str
    this.setData({
      fileArr: relArr
    })
  },
  //删除录音
  onDel(e){
    let id = e.currentTarget.dataset.itemid
    let newVoices = ''
    let voiceArr = this.data.record
    debugger
    voiceArr.splice(id, 1)
    debugger
    voiceArr.forEach((item,index) =>{
      if(item === ""){
        voiceArr.splice(index, 1)
      }
      else if(item){
        if (!newVoices) {
          newVoices = item + ','
        } else {
          newVoices = newVoices + item + ',' 
        }
      }
    })
    debugger
    this.setData({
      allFileArr: newVoices,
      tempVoice: newVoices,
      record: voiceArr
    })
  },
  //开始录音
  startRecord() {
    var aa = 0
    var self = this
    const recorderManager = wx.getRecorderManager()
    const options = {
      duration: 60000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'mp3',
    }
    this.setData({
      startRecord: !this.data.startRecord
    })
    if (this.data.startRecord) {
      timeAuto = setInterval(() => {
        this.setData({
          startRecordTime: this.data.startRecordTime + 1
        })
      }, 1000);
      recorderManager.start(options)
    } else {
      recorderManager.stop(options)
      clearInterval(timeAuto)
      this.setData({
        startRecordTime: 0
      })
    }
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    recorderManager.onError((e)=>{
      if(aa === 0){
        console.log(e)
        recorderManager.stop(options)
        clearInterval(timeAuto)
        self.setData({
          startRecordTime: 0
        })
        self.checkRecord()
      }
      aa ++
    })
    recorderManager.onStop((res) => {
      const {
        tempFilePath
      } = res
      var voiceItem = {
        name: allVoice.length + 1,
        path: tempFilePath,
        isPlay: false
      }
      this.uploadVoice(voiceItem)
      allVoice.push(voiceItem)
      this.setData({
        tempVoice: allVoice
      })
    })
  },
  uploadVoice(e) {
    var self = this
    var url = api.SecretUpload_file
    var token = getToken()
    wx.uploadFile({
      url: url, //仅为示例，非真实的接口地址
      filePath: e.path,
      name: 'file',
      formData: {
        'access_token': token,
        'size': 0.1
      },
      success: function (res) {
        debugger
        var data = JSON.parse(res.data)
        if (data.code === 0) {
          self.setData({
            allFileArr: self.data.allFileArr + data.data.file + "," ,
            record: self.data.record.concat(data.data.file)
          })
        }
      }
    })
  },
  // onTab(e) {
  //   this.setData({
  //     classId: Number(e.currentTarget.dataset.id)
  //   })
  // },
  changeInput(e) {
    var num = e.detail.cursor
    this.setData({
      textNowL: num,
      content: e.detail.value
    })
  },
  // 上传文件
  upload() {
    wx.getSavedFileList({
      success: function (res) {
        console.log(res.fileList)
      }
    })
  }
})